package com.course.servlet;

import com.course.entity.Course;
import com.course.service.CourseService;
import com.course.dao.GuanliyuanCourseDAO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/guanliyuan_course_manage")
public class GuanliyuanCourseManageServlet extends HttpServlet {
    private CourseService courseService;

    @Override
    public void init() throws ServletException {
        super.init();
        this.courseService = new CourseService(new GuanliyuanCourseDAO());
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Clear any previous messages from the session when the page is loaded via GET
        request.getSession().removeAttribute("successMessage");
        request.getSession().removeAttribute("errorMessage");

        List<Course> courses = courseService.getAllCourses();
        request.setAttribute("courses", courses);
        request.getRequestDispatcher("/guanliyuan_course_manage.jsp").forward(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");

        if ("delete".equals(action)) {
            String courseIdStr = request.getParameter("id");
            try {
                int courseId = Integer.parseInt(courseIdStr);
                boolean success = courseService.deleteCourse(courseId);

                if (success) {
                    request.getSession().setAttribute("successMessage", "课程删除成功！");
                } else {
                    request.getSession().setAttribute("errorMessage", "课程删除失败，请稍后重试。");
                }
            } catch (NumberFormatException e) {
                request.getSession().setAttribute("errorMessage", "无效的课程ID。");
            } catch (Exception e) {
                request.getSession().setAttribute("errorMessage", "删除课程时发生错误：" + e.getMessage());
                e.printStackTrace();
            }
        }
        // Redirect back to the course management page to display updated list and messages
        response.sendRedirect(request.getContextPath() + "/guanliyuan_course_manage");
    }
} 